import 'package:flutter/material.dart';
import 'package:flutter_study/utils/SharePrefencesUtils.dart';
import 'package:flutter_study/utils/Toast.dart';

class SharePrefrencePage extends StatefulWidget {
  const SharePrefrencePage({Key key}) : super(key: key);

  @override
  _SharePrefrencePageState createState() => _SharePrefrencePageState();
}

class _SharePrefrencePageState extends State<SharePrefrencePage> {
  TextEditingController editingControllerWrite =
      new TextEditingController(text: "");
  TextEditingController editingControllerRead =
      new TextEditingController(text: "");
  bool isOpen = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    SharePreferencesUtils.init();
    editingControllerRead.text = SharePreferencesUtils.getString("key");
    isOpen = SharePreferencesUtils.getBool("isOpen");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("SharePreference"),
      ),
      body: Padding(
        padding: EdgeInsets.all(20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TextField(
              controller: editingControllerWrite,
              decoration: InputDecoration(hintText: "请输入存储内容"),
            ),
            ElevatedButton(
                onPressed: () {
                  SharePreferencesUtils.prefs
                      .setString("key", editingControllerWrite.text)
                      .then((value) {
                    if (value) {
                      Toast.toast(context, msg: "保存成功");
                    } else {
                      Toast.toast(context, msg: "保存失败");
                    }
                  });
                },
                child: Text("保存")),
            TextField(
              controller: editingControllerRead,
              enabled: false,
              decoration: InputDecoration(),
            ),
            ElevatedButton(
                onPressed: () {
                  editingControllerRead.text =
                      SharePreferencesUtils.prefs.getString("key");
                },
                child: Text("查询")),
            Switch(
                value: isOpen,
                onChanged: (value) async {
                  await SharePreferencesUtils.setBool("isOpen", value)
                      .then((value) {
                    if (value) {
                      Toast.toast(context, msg: "保存成功");
                      setState(() {
                        isOpen = SharePreferencesUtils.getBool("isOpen");
                      });
                    } else {
                      Toast.toast(context, msg: "保存失败");
                    }
                  });
                })
          ],
        ),
      ),
    );
  }
}
